// 控件拖拽操作
import { computed } from 'vue'
import { useEditStore } from '@/store'

export default function useWidgetDraggable() {
    const editStore = useEditStore()

    // 拖动的控件
    const draggableWidget = computed({
        get: () => editStore.draggableWidget,
        set: val => editStore.draggableWidget = val
    })

    // 拖动的控件类型
    const draggableWidgetType = computed(() => draggableWidget.value.widgetType || '')

    const groupName = 'widgets-group'
    const draggableHandleName = 'draggable-handle'
    let disabled = false

    // 模板控件拖拽属性配置
    const templateDraggableConfig = computed(() => ({
        group: {
            name: groupName,
            pull: 'clone',
            put: false
        },
        sort: false,
        animation: 0,
        disabled,
        onStart(e) {
            const { type } = e.item['__draggable_context'].element.eles
            draggableWidget.value = {
                from: 'template',
                widgetType: type
            }
        },
        // move(e) {
        //     // const { draggedContext, relatedContext } = e
        //     // if (relatedContext.list?.[draggedContext.futureIndex - 1]?.eles?.type === 'bbs') {
        //     //     return false
        //     // }
        //     return true
        // },
        onEnd(e) {
            onResetDraggableWidget()
        }
    }))

    // 控件拖拽属性配置
    const draggableConfig = computed(() => ({
        group: groupName,
        ghostClass: 'draggable-ghost', // 放置占位符的类名
        chosenClass: 'draggable-chosen',  // 所选项目的类名
        dragClass: 'draggable-drag',  // 拖动项的类名
        animation: 200,
        disabled,
        itemKey: e => e.eles.id,
        handle: `.${draggableHandleName}`,
        onStart(e) {
            const { id, type } = e.item['__draggable_context'].element.eles
            draggableWidget.value = {
                from: 'list',
                widgetType: type,
                widgetId: id
            }
        },
        // move(e) {
        //     const { draggedContext, relatedContext } = e
        //     console.log(draggedContext.futureIndex, relatedContext.index)
        //     return true
        // },
        onEnd(e) {
            onResetDraggableWidget()
        }
    }))

    // 重置拖动控件
    const onResetDraggableWidget = () => {
        draggableWidget.value = {
            from: '',
            widgetType: '',
            widgetId: ''
        }
    }

    return {
        draggableWidget,
        draggableWidgetType,
        draggableHandleName,
        templateDraggableConfig,
        draggableConfig
    }
}